package com.huang.wangpan.provider;

import com.alibaba.fastjson.JSON;
import com.huang.wangpan.dto.AccessTokenDTO;
import com.huang.wangpan.dto.GithubUser;
import com.huang.wangpan.utils.HttpUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class GithubProvider {
    private static final Logger logger = LoggerFactory.getLogger(GithubProvider.class);

    public String getAccessToken(AccessTokenDTO aTokenDTO) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();
        String json = JSON.toJSONString(aTokenDTO);
        logger.info(json);

        RequestBody body2 = RequestBody.create(json, mediaType);
        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token?code=" + aTokenDTO.getCode() + "&state=" + aTokenDTO.getState()
                        + "&client_id=" + aTokenDTO.getClinet_id() + "&client_secret=" + aTokenDTO.getClient_secret() + "&redirect_uri=" + aTokenDTO.getRedirect_uri())
                .build();
        logger.info(request.toString());
        try {
            Response response = client.newCall(request).execute();
            String responseStr = response.body().string();
            String access_token = responseStr.split("&")[0].split("=")[1];
            logger.info("access_token:= {}", access_token);
            logger.info("responseStr:= {}", responseStr);
            return access_token;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public GithubUser getUser(String access_token) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user?access_token=" + access_token)
                .build();
        try {
            Response reponse = client.newCall(request).execute();
            String string = reponse.body().string();
            GithubUser githubUser = JSON.parseObject(string, GithubUser.class);
            return githubUser;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 使用Http请求
     *
     * @param aTokenDTO
     * @return GithubUser
     */
    public GithubUser getAccessTokenAndGithubUser(AccessTokenDTO aTokenDTO) {
        String state = aTokenDTO.getState();
        String code = aTokenDTO.getCode();
        String clinet_id = aTokenDTO.getClinet_id();
        String client_secret = aTokenDTO.getClient_secret();
        String redirect_uri = aTokenDTO.getRedirect_uri();

        // Step2：通过 Authorization Code 获取 AccessToken
        String githubAccessTokenResult = HttpUtil.sendGet("https://github.com/login/oauth/access_token",
                "client_id=" + clinet_id
                        + "&client_secret=" + client_secret
                        + "&code=" + code
                        + "&redirect_uri=" + redirect_uri
                        + "&state=" + state);

        logger.info("==>githubAccessTokenResult: {}", githubAccessTokenResult);

        /**
         * access_token=b9e5c3d64774ebd45856a68120f0ad7840775a24&scope=user&token_type=bearer
         * access_token=35b4abb2f7fc808e1206f331b29d7e67048b4ff5&scope=&token_type=bearer
         */
        String[] githubResultArr = githubAccessTokenResult.split("&");
        Map<String, Object> paramMap = new HashMap<>();
        for (String element : githubResultArr) {
            String[] split = element.split("=");
            if (split.length >= 2) {
                paramMap.put(split[0], split[1]);
            }
        }

        // Step2：通过 access_token 获取用户信息
        String githubInfoResult = HttpUtil.sendGet("https://api.github.com/user", "access_token=" + paramMap.get("access_token"));
        GithubUser githubUser = JSON.parseObject(githubInfoResult, GithubUser.class);
        return githubUser;
    }

}
